<?php
function register()
{
    if (empty($_POST['username'])) {
        $arr = array("message" => "请输入账号", "code" => 0);
        print_r(json_encode($arr));
        return;
    }
    if (empty($_POST['password'])) {
        $arr = array("message" => "请输入密码", "code" => 0);
        print_r(json_encode($arr));
        return;
    }
    $uname = $_POST['username'];
    $pword = $_POST['password'];

    $link = mysqli_connect('127.0.0.1', 'root', 'root', 'demo1');

    $res = mysqli_query($link, "SELECT * FROM `users` WHERE `username` = '$uname'");

    $row = mysqli_fetch_assoc($res);

    if ($row) {
        $arr = array("message" => "该账号已存在！重新输入", "code" => 0);
        print_r(json_encode($arr));
        return;
    }
    $query = mysqli_query($link, "INSERT INTO `users` (`username`, `password`) VALUES('$uname', '$pword')");

    mysqli_close($link);
    if ($query) {
        $arr = array("message" => "注册成功", "code" => 1);
    } else {
        $arr = array("message" => "注册失败", "code" => 0);
    }
    // 把这关联型数组返回
    print_r(json_encode($arr));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    register();
}
